#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QMessageBox>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("Server Port:8888");
    //分配空间
    m_tcpServer = new QTcpServer(this);
    m_tcpSocket = new QTcpSocket(this);

    //ui->buttonSend->setEnabled(false);
    //ui->buttonClose->setEnabled(false);
    //QHostAddress::Any 所有网卡
    bool isOk = m_tcpServer->listen(QHostAddress::Any,8888);
    if(isOk)
    {
        qDebug() << "success";
    }
    ui->textEditWrite->clear();
    //有客户端请求会触发newConnection，通过 newConnection 信号连接槽函数
    connect(m_tcpServer,&QTcpServer::newConnection,[=](){
        //激活发送按钮和关闭按钮
        qDebug() << "newConnect";
        ui->buttonSend->setEnabled(true);
        ui->buttonClose->setEnabled(true);
        //取出建立好连接的套接字,新的连接
        m_tcpSocket = m_tcpServer->nextPendingConnection();
        //获取对方的IP 和端口
        QString ip = m_tcpSocket->peerAddress().toString();
        qint16 port = m_tcpSocket->peerPort();
        QString temp = QString("[%1:%2]:连接成功").arg(ip).arg(port);
        ui->textEditRead->setText(temp);

        //服务端接收客户端信息 ，当客户端发送信息接收完成后会触发readyRead信号
        connect(m_tcpSocket,&QTcpSocket::readyRead,[=](){
            //从通讯套接字中取出内容
            QByteArray array = m_tcpSocket->readAll();
            array.insert(0,"Client: ");
            ui->textEditRead->append(array);

        });
    });


}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_buttonSend_clicked()
{
   //获取编辑区内容
    qDebug()<<"send";
   QString str =ui->textEditWrite->toPlainText();
   if(str.isEmpty())
   {
       QMessageBox mybtn(QMessageBox::Warning,QString("Info"),QString("Send Context is Empty"));
       mybtn.setStandardButtons(QMessageBox::Yes);
       mybtn.setButtonText(QMessageBox::Yes,QString("OK"));
       if(QMessageBox::Yes == mybtn.exec())
       {
           return;
       }
   }
   ui->textEditWrite->clear();
   //给对方发送数据，使用套接字 m_tcpSocket
   m_tcpSocket->write(str.toUtf8().data());
}

void Widget::on_buttonClose_clicked()
{
    //主动和客户端端口连接
    qDebug()<<"close";
    ui->textEditWrite->clear();
    m_tcpSocket->disconnectFromHost();
    m_tcpSocket->close();
}
